/**
 * 
 */
package org.heydr.remote.impl;



import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.heydr.datacenter.db.DataAccess;
import org.heydr.datacenter.db.DataPool;
import org.heydr.datacenter.guard.Guard;
import org.heydr.datacenter.util.StringUtils;
import org.heydr.entity.Info;
import org.heydr.entity.Site;
import org.heydr.entity.Task;
import org.heydr.entity.Url;
import org.heydr.remote.RMIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service(value="rmiServiceImpl")
public class RMIServiceImpl implements RMIService{
	
	private Lock lock =  new ReentrantLock(true);
	
	@Autowired
	private Guard guard;
	
//	@PostConstruct
//	public void init(){
//		List<Url> urlMD5s = dataAccess.fetchUrlMD5();
//		for(Url url:urlMD5s){
//			DataPool.addDuplicateData(url.getSite(), url.getUrlMd5());
//		}
//	}
	
	@Autowired
	private DataAccess dataAccess;
	
	@Override
	public List<Site> availableSites() {
		List<Site> sites = dataAccess.availableSiteInfos();
		List<Url> urls = new ArrayList<Url>();
		for(Site s : sites){
			String entryUrl = s.getEntryUrl();
			String urlMd5 = StringUtils.md5(entryUrl);
			boolean isDuplicate = DataPool.isDuplicate(s.getSite(), urlMd5);
			if(!isDuplicate){
				Url url = new Url();
				url.setUrl(entryUrl);
				url.setType(1);
				url.setParentUrl(entryUrl);
				url.setEntryUrl(entryUrl);
				url.setFailTimes(0);
				url.setStatus(0);
				url.setUrlMd5(urlMd5);
				url.setSite(s.getSite());
				urls.add(url);
			}
		}
		if(urls.size()>0)
			dataAccess.storeUrls(urls);
		return sites;
	}
	
	@Override
	public Task availableTasks(String ip,int size){
		guard.heartBeat(ip);
		lock.lock();
		Task task = null;
//		CoreMeta coreMeta = guard.getCore(ip);
//		List<Url> urls = dataAccess.fetchTasks(coreMeta.getMod(), coreMeta.getTotal(), size);
		lock.unlock();
		return task;
	}

	@Override
	public void storeInfos(List<Info> infos) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void finishedTasks(List<Url> urls) {
		dataAccess.finishedTasks(urls);
	}

}
